package com.site.wisdom_construction.util.imgUtil;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Description
 * @Author daiyifei
 * @Date 2021-12-06
 */
public class CodeImgUtil {
    public String CodeImgUtil(String content){
        try {
            //String path = "/root/img/";
            String path = "D:/QRcode/";

            //二维码工具类
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            @SuppressWarnings("rawtypes")
            Map hints = new HashMap();
            //设置UTF-8， 防止中文乱码
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            //设置二维码四周白色区域的大小
            hints.put(EncodeHintType.MARGIN, 0);
            //设置二维码的容错性
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

            //width:图片完整的宽;height:图片完整的高
            //因为要在二维码下方附上文字，所以把图片设置为长方形（高大于宽）
            int width = 400;
            int height = 460;

            //画二维码，记得调用multiFormatWriter.encode()时最后要带上hints参数，不然上面设置无效
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

            String uuid = UUID.randomUUID().toString().replaceAll("-" , "");
            String tempFileName = uuid + ".jpg";
            //qrcFile用来存放生成的二维码图片（无logo，无文字）
            File qrcFile = new File(path, tempFileName);

            //开始画二维码
            MatrixToImageWriter.writeToFile(bitMatrix, "jpg" , qrcFile);
            try {
                //填写文件地址
                String Host = "codeImg";
                //上传到OSS
                String uploadUrl = AliyunOSSUtil.upload(qrcFile, Host);
                //删除缓存文件减少储存空间
                qrcFile.delete();
                return uploadUrl;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return "创建失败";
        } catch (Exception e) {
            e.printStackTrace();
            return "创建失败";
        }
    }

}
